<template>
  <view class="chat-container">
    <!-- 聊天消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-with-animation="true"
      :scroll-top="scrollTop"
    >
      <view 
        v-for="(message, index) in messages" 
        :key="index"
        :class="['message-item', message.sender]"
      >
        <!-- 头像 -->
        <image 
          class="avatar"
          :src="message.sender === 'user' ? userAvatar : serviceAvatar"
        ></image>
        <!-- 消息气泡 -->
        <view class="message-bubble">
          <text class="message-text">{{ message.content }}</text>
        </view>
      </view>
    </scroll-view>
    <!-- 消息输入区域 -->
    <view class="input-area">
      <input 
        class="message-input"
        v-model="inputMessage"
        placeholder="输入消息..."
        @confirm="sendMessage"
      />
      <button 
        class="send-button"
        @click="sendMessage"
        :disabled="!inputMessage.trim()"
      >
        <uni-icons type="paperplane" size="22" color="#fff"></uni-icons>
      </button>
    </view>
  </view>
</template>

<script>
import { useMsgStore } from '@/store/message'
import { useUserStore } from '../../store/user';
const userStore = useUserStore()
const msgStore = useMsgStore()
export default {
  setup() {
    return{
      userStore,
      msgStore
    }
  },
  onLoad() {
    this.connectSocket()
  },
  onUnload(){
    this.closeSocket()
  },
  data() {
    return {
      socketOpen: false,
      messages: [
        { 
          sender:'service',
          content: '您好，请问有什么可以帮您？',
        }
      ],
      inputMessage: '',
      scrollTop: 0,
      userAvatar: '/static/default-avatar.png',
      serviceAvatar: '/static/default-avatar.png'
    };
  },
  methods: {
    connectSocket() {
      wx.connectSocket({
        url: `ws://localhost:8080/ws/user/reminder/${this.userStore.userInfo.id}`,
        header: {
          'Content-Type': 'application/json',
          'authentication': this.userStore.getUserToken // 确保调用方法获取 token
        },
        success:(res)=>{
          console.log('建立连接成功');
          this.socketOpen = true
          // const msg = '你好'
          // wx.sendSocketMessage({
          //   data: JSON.stringify(msg),
          //   success: () => {
          //     console.log('消息发送成功');
          //   }
          // })
        }
      });
      // wx.onSocketOpen((res) => {
      //   console.log(2);
      //   this.socketOpen = true;
      //   console.log('WebSocket 连接已打开');
      // });
    },
    sendMessage() {
      if (!this.inputMessage.trim()) return;
      const message = {
        targetId: 1, // 写死为1
        content: this.inputMessage
      };
      this.messages.push({
        sender: 'user',
        content: this.inputMessage
      });
      this.sendSocketMessage(message);
      this.inputMessage = '';
      this.scrollToBottom();
    },
    sendSocketMessage(message) {
      if (this.socketOpen) {
        wx.sendSocketMessage({
          data: JSON.stringify(message),
          success: (res) => {
            console.log('消息发送成功');
            console.log(res);
          },
          fail: (error) => {
            console.error('消息发送失败:', error);
          }
        });
      } else {
        console.error('WebSocket 连接未打开，无法发送消息');
      }
    },
    scrollToBottom() {
      setTimeout(() => {
        this.scrollTop = this.scrollTop + 1;
      }, 100);
    },
    closeSocket() {
      if (this.socketOpen) {
        wx.closeSocket();
      }
    }
  }
};
</script>

<style lang="scss">
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f6fa;
  padding-bottom: 400rpx;
}

.message-list {
  flex: 1;
  padding-bottom: 200rpx;
  margin-bottom: 400rpx;
}

.message-item {
  display: flex;
  margin-bottom: 40rpx;
  transition: all 0.3s ease;

  &.user {
    flex-direction: row-reverse;
    
    .message-bubble {
      background: #2ac2d1;
      border-radius: 24rpx 24rpx 4rpx 24rpx;
      
      .message-text {
        color: white;
      }
    }
  }
  
  &.service {
    .message-bubble {
      background: white;
      border-radius: 24rpx 24rpx 24rpx 4rpx;
      box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
    }
  }
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin: 0 20rpx;
}

.message-bubble {
  max-width: 500rpx;
  padding: 20rpx 28rpx;
  position: relative;
  
  .message-text {
    font-size: 30rpx;
    line-height: 1.5;
  }
}

.input-area {
  position: fixed;
  bottom: 0;
  width: 100%;
  // 调整输入区域内边距
  padding: 20rpx 0 20rpx 0; 
  background: white;
  display: flex;
  align-items: center;
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.05);
}

.message-input {
  flex: 1;
  background: #f8f9fa;
  height: 80rpx;
  padding: 0 30rpx;
  border-radius: 40rpx;
}

.send-button {
  // 适当减小按钮尺寸
  width: 70rpx; 
  height: 70rpx;
  border-radius: 50%;
  background: #2ac2d1;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.9);
    opacity: 0.8;
  }
}
</style>